﻿#include "signup.h"
#include "ui_signup.h"
#include "networkcommunication.h"

#include <QMessageBox>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>


signup::signup(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::signup)
{
    ui->setupUi(this);
    server = NetworkConnect::connectserver()->getconserver();
    connect(NetworkConnect::connectserver(), SIGNAL(user_signup(const QByteArray &)),
                                        this, SLOT(handle(const QByteArray &)));
}

signup::~signup()
{
    delete ui;
}

/*json登录格式：
 * {
 * "command" : "user_signup",
 * "username" : "用户名",
 * "userid" : "id"
 * "passwd" : "密码",
 * "question" : "密保",
 * "sex"   : "性别"
 * }
 * */

void signup::on_pushButton_signup_clicked()
{
    QString userid = ui->lineEdit_id->text();
    QString username = ui->lineEdit_username->text();
    QString passwd   = ui->lineEdit_passwd->text();
    QString question = ui->lineEdit_question->text();
    QString sex = ui->radioButton_man->isChecked() ? "man" : "woman";

    QJsonObject req_obj;
    req_obj.insert("command", "user_signup");
     req_obj.insert("userid", userid);
    req_obj.insert("username", username);
    req_obj.insert("passwd", passwd);
    req_obj.insert("question", question);
    req_obj.insert("sex", sex);


    QJsonDocument req_js(req_obj);

    server->write(req_js.toJson());
}

void signup::handle(const QByteArray &mess)
{

    QJsonDocument js = QJsonDocument::fromJson(mess);
    QJsonObject obj = js.object();
    qDebug() << js;
    if(obj.value("isallowed").toBool())
    {
        QMessageBox::information(this, "成功", "注册成功");
        this->close();
        return;
    }
    else
    {
        QMessageBox::information(this, "失败", obj.value("errmessage").toString());
        return;
    }
}


void signup::on_pushButton_cancel_clicked()
{
    this->close();
}

